package com.util;

import org.apache.commons.codec.binary.Hex;

import java.security.MessageDigest;

public class MD5Utils {
    private static final String SALT = "23543dfggeelysdafaqj23ou89ZXcj@#$@#$#@KJdjklj;D../dSF.,";

    /**
     * 加盐MD5加密
     * <p>
     *
     * @Title : getSaltMD5
     * </p>
     * <p>
     * @Description : TODO
     * </p>
     */
    public static String getSaltMD5(String password) {

        // 生成最终的加密盐

        password = md5Hex(password + SALT);
        char[] cs = new char[48];
        for (int i = 0; i < 48; i += 3) {
            cs[i] = password.charAt(i / 3 * 2);
            char c = SALT.charAt(i / 3);
            cs[i + 1] = c;
            cs[i + 2] = password.charAt(i / 3 * 2 + 1);
        }
        return String.valueOf(cs);
    }

    /**
     * 使用Apache的Hex类实现Hex(16进制字符串和)和字节数组的互转
     * <p>
     *
     * @Title : md5Hex
     * </p>
     * <p>
     * @Description : TODO
     * </p>
     */
//    @SuppressWarnings("unused")
    private static String md5Hex(String str) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] digest = md.digest(str.getBytes());
            return new String(new Hex().encode(digest));
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e);
            return "";
        }
    }


}